using Volo.Abp.Data;
using Volo.Abp.DependencyInjection;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.Guids;
using Volo.Abp.OpenIddict.Applications;

using WL.Think.Sample.Books;

namespace WL.Think.Sample;

public class SampleDataSeederContributor
    : IDataSeedContributor, ITransientDependency
{
    private readonly IRepository<BookEntity,Guid> _bookRepository;
    private readonly IGuidGenerator _idGenerator;
    private readonly AbpApplicationManager _applicationManager;
    private readonly IOpenIddictApplicationRepository _applicationRepository;

    public SampleDataSeederContributor(
        IRepository<BookEntity, Guid> bookRepository,
        IGuidGenerator idGenerator,
        AbpApplicationManager applicationManager,
        IOpenIddictApplicationRepository applicationRepository)
    {
        _bookRepository = bookRepository;
        _idGenerator = idGenerator;
        _applicationManager = applicationManager;
        _applicationRepository = applicationRepository;
    }

    public async Task SeedAsync(DataSeedContext context)
    {
        //await TestOpenIddictApplication();
        if (await _bookRepository.GetCountAsync() <= 0)
        {
            var book = new BookEntity(_idGenerator.Create())
            {
                Name = "1984",
                Type = BookType.Dystopia,
                PublishDate = new DateTime(1949, 6, 8),
                Price = 19.84f
            };
            await _bookRepository.InsertAsync( book,autoSave: true);

            book = new BookEntity(_idGenerator.Create())
            {
                Name = "The Hitchhiker's Guide to the Galaxy",
                Type = BookType.ScienceFiction,
                PublishDate = new DateTime(1995, 9, 27),
                Price = 42.0f
            };
            await _bookRepository.InsertAsync(book,autoSave: true);
        }
    }

    public async Task TestOpenIddictApplication()
    {
        var item = await _applicationRepository.GetAsync(Guid.Parse("3a1bfd6c-068c-7626-ae14-2961813995c8"));
        var descriptor = new AbpApplicationDescriptor();
        await _applicationManager.PopulateAsync(descriptor, item.ToModel());
        var permissions = descriptor.Permissions;
    }
}